from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import pymysql
import json

# 数据库连接（参考facecontroller）
def get_conn():
    return pymysql.connect(
        host='119.29.249.72',
        port=3306,
        user='root',
        password='123456cdut',
        database='facedetection',
        charset='utf8'
    )

# 登录接口
@csrf_exempt
def login(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        username = data.get('username')
        password = data.get('password')

        conn = get_conn()
        cursor = conn.cursor()
        sql = "SELECT * FROM user_info WHERE user_name=%s AND password=%s"
        cursor.execute(sql, (username, password))
        result = cursor.fetchone()
        conn.close()

        if result:
            return JsonResponse({"status": "success", "message": "登录成功"})
        else:
            return JsonResponse({"status": "fail", "message": "用户名或密码错误"})
    else:
        return JsonResponse({"status": "fail", "message": "仅支持POST请求"})

# 注册接口
@csrf_exempt
def register(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        username = data.get('username')
        password = data.get('password')
        age = data.get('age', None)
        phone = data.get('phone', None)

        conn = get_conn()
        cursor = conn.cursor()

        # 检查用户名是否存在
        cursor.execute("SELECT * FROM user_info WHERE user_name=%s", (username,))
        if cursor.fetchone():
            conn.close()
            return JsonResponse({"status": "fail", "message": "用户名已存在"})

        # 插入新用户
        sql = "INSERT INTO user_info (user_name, password, age, phone) VALUES (%s, %s, %s, %s)"
        cursor.execute(sql, (username, password, age, phone))
        conn.commit()
        conn.close()

        return JsonResponse({"status": "success", "message": "注册成功"})
    else:
        return JsonResponse({"status": "fail", "message": "仅支持POST请求"})
